package com.jetbrains.licenseService.util;


import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;


final class ObjectPool<T> {
    private final List<ObjectPool<T>.Entry> a;
    private final Factory<T> b;

    private final class Entry
            implements ObjectPool.Item<T> {
        private final AtomicBoolean a = new AtomicBoolean(false);
        @NotNull
        private final T b;

        Entry() {
            this.b = localObject;
        }

        boolean alloc() {
            boolean bool = !this.a.getAndSet(true);
            if (bool) {
                ObjectPool.this.b.onAllocate(this.b);
            }
            return bool;
        }

        public void release() {
            ObjectPool.this.b.onRelease(this.b);
            this.a.set(false);
        }

        @NotNull
        public T get() {
            Object tmp4_1 = this.b;
            if (tmp4_1 == null) {
                throw new IllegalStateException(String.format("@NotNull method %s.%s must not return null", new Object[]{"com/jetbrains/licenseService/util/ObjectPool$Entry", "get"}));
            }
            return tmp4_1;
        }
    }

    ObjectPool(int paramInt, Factory<T> paramFactory) {
        this.b = paramFactory;
        this.a = new ArrayList();
        for (int i = 0; i < paramInt; i++) {
            this.a.add(new Entry(paramFactory.create()));
        }
    }

    public Item<T> allocate() {
        for (final Object localObject = this.a.iterator(); ((Iterator) localObject).hasNext(); ) {
            Entry localEntry = (Entry) ((Iterator) localObject).next();
            if (localEntry.alloc()) {
                return localEntry;
            }
        }
        localObject = this.b.create();
        this.b.onAllocate(localObject);
        new Item() {
            @NotNull
            public T get() {
                Object tmp4_1 = localObject;
                if (tmp4_1 == null) {
                    throw new IllegalStateException(String.format("@NotNull method %s.%s must not return null", new Object[]{"com/jetbrains/licenseService/util/ObjectPool$1", "get"}));
                }
                return tmp4_1;
            }

            public void release() {
                ObjectPool.this.b.onRelease(localObject);
            }
        };
    }

    public static abstract interface Item<Data> {
        @NotNull
        public abstract Data get();

        public abstract void release();
    }

    public static abstract interface Factory<Data> {
        public abstract Data create();

        public abstract void onAllocate(Data paramData);

        public abstract void onRelease(Data paramData);
    }
}
